import React, { Component } from 'react'
import {
  Form, Button, Col, Row, DatePicker,
  Input, Select, message,
} from 'antd'
import moment from 'moment'

import { address } from '@/Utils/apiConfig'
import request from '@/Utils/fecth'
import regexp from '@/Utils/regexp'
import { cryptoData } from '@/Utils/common'

import './index.less'

const { Option } = Select

export default class Register extends Component {
  constructor(props) {
    super(props)
    this.state = {
      show: false,
      login_res: true, // 登录状态
      errorLocal: '',
      loading: false,
    }
    this.publicKey = ''
    this.handleRecord = {}
  }

  componentDidMount() {
    this.getPublicKey()
  }

  async getPublicKey() {
    const { status, data } = await request().get(address.getPublicKey)
    if (status === 200) {
      this.publicKey = data || ''
    }
  }

  onOk = async(values) => {
    const { expireTime } = values || {}
    const { publicKey } = this.props
    const params = {
      ...values,
      expireTime: expireTime ? moment(expireTime).format('YYYY-MM-DD HH:mm:ss') : '',
    }
    const data = cryptoData(JSON.stringify(params), publicKey)
    const { code } = await request().post(address.register, data)
    if (code === 200) {
      message.success('注册成功')
    }
  }

  render() {
    const { loading } = this.state
    return (
      <div className="register_page">
        <div className="login_form">
          <Form
            ref={c => { this.addForm = c }}
            {...{
              labelCol: { span: 8 },
              wrapperCol: { span: 16 },
            }}
            colon={false}
            autoComplete="false"
            onFinish={this.onOk}
          >
            <Row>
              <Col span={12}>
                <Form.Item
                  label="姓名："
                  name="identity_name"
                  initialValue={this.handleRecord.identity_name || ''}
                  rules={[
                    { required: true, message: '请输入用户名' },
                  ]}>
                  <Input maxLength={30} placeholder="请输入用户名" />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  label="角色："
                  name="role"
                  initialValue={this.handleRecord.role || null}
                  rules={[
                    { required: true, message: '请选择角色' },
                  ]}>
                  <Select placeholder="请选择角色">
                    <Option value={'00000000000000000000000000000001'}>超级管理员</Option>
                  </Select>
                </Form.Item>
              </Col>
            </Row>
            <Row>
              <Col span={12}>
                <Form.Item
                  label="登录用户名："
                  name="name"
                  initialValue={this.handleRecord.name || ''}
                  rules={[
                    { required: true, message: '请输入登录用户名' },
                    {
                      type: 'string',
                      pattern: /^[a-zA-Z]{6,20}$/,
                      max: 20,
                      min: 6,
                      message: '请输入6-20位的英文用户名',
                    },
                  ]}>
                  <Input
                    disabled={this.flag === 'update'}
                    maxLength={30}
                    placeholder="请输入登录用户名" />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  label="邮箱："
                  name="mail_address"
                  initialValue={this.handleRecord.mail_address || ''}
                  rules={[
                    { required: true, message: '请输入邮箱' },
                    {
                      pattern: regexp.email,
                      message: '请输入正确的邮箱地址',
                    },
                  ]}>
                  <Input maxLength={30} placeholder="请输入邮箱" />
                </Form.Item>
              </Col>
            </Row>
            {
              this.flag !== 'update' &&
              <Row>
                <Col span={12}>
                  <Form.Item
                    label="密码："
                    name="_pwd"
                    initialValue={this.handleRecord._pwd || ''}
                    validateFirst
                    rules={[
                      { required: true, message: '请输入密码' },
                      {
                        type: 'string',
                        min: 8,
                        pattern: regexp._pwd,
                        message: '密码须为8位以上字母数字与特殊字符的组合',
                      },
                    ]}>
                    <Input.Password disabled={this.flag === 'update'} maxLength={30} placeholder="请输入密码" />
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <Form.Item
                    dependencies={['_pwd']}
                    label="确认密码："
                    name="confirm__pwd"
                    initialValue={this.handleRecord.confirm__pwd || ''}
                    validateFirst
                    rules={[
                      { required: true, message: '请输入密码' },
                      {
                        type: 'string',
                        min: 8,
                        pattern: regexp._pwd,
                        message: '密码须为8位以上字母数字与特殊字符的组合',
                      },
                      ({ getFieldValue }) => ({
                        validator(_, value) {
                          if (!value || getFieldValue('_pwd') === value) {
                            return Promise.resolve()
                          }
                          return Promise.reject(new Error('密码两次输入不一致'))
                        },
                      }),
                    ]}>
                    <Input.Password disabled={this.flag === 'update'} maxLength={30} placeholder="请输入密码" />
                  </Form.Item>
                </Col>
              </Row>
            }

            <Form.Item
              name="id_card"
              label="身份证号码："
              labelCol={{ span: 4 }}
              wrapperCol={{ span: 20 }}
              rules={[
                {
                  required: true,
                  message: '请输入身份证号码',
                },
                {
                  pattern: regexp.idCard,
                  message: '请输入正确的身份证号码',
                },
              ]}
            >
              <Input maxLength={30} className="input" placeholder="请输入身份证号码" />
            </Form.Item>
            <Row>
              <Col span={12}>
                <Form.Item
                  name="temporary"
                  label={<span>
                    账户类型
                    ：
                  </span>}
                  rules={[{
                    required: true,
                    message: '请选择账户类型',
                  }]}
                >
                  <Select placeholder="请选择">
                    <Option value={0}>长期有效账户</Option>
                    <Option value={1}>临时账户</Option>
                  </Select>
                </Form.Item>
              </Col>
              {
                <Col span={10} style={{ marginLeft: '8px' }}>
                  <Form.Item
                    noStyle
                    dependencies={['temporary']}
                  >
                    {
                      ({ getFieldValue }) => {
                        return getFieldValue('temporary') === 1 && <Form.Item
                          name="expireTime"
                          rules={[{
                            required: true,
                            message: '请填写有效天数',
                          }]}
                          extra={'账户的失效日期'}
                          wrapperCol={{
                            span: 20,
                          }}
                        >
                          <DatePicker
                            style={{ width: '200px' }}
                            showTime
                            format="YYYY-MM-DD HH:mm:ss"
                            disabledDate={current => {
                              return current && (current > moment().add(90, 'days').endOf('day') || current < moment().endOf('day'))
                            }}
                          />
                        </Form.Item>
                      }
                    }
                  </Form.Item>
                </Col>
              }
            </Row>
            <Form.Item
              name="description"
              label="备注："
              initialValue={this.handleRecord.description || ''}
              labelCol={{ span: 4 }}
              wrapperCol={{ span: 20 }}
            >
              <Input.TextArea maxLength={150} rows={5} className="input" placeholder="请输入备注" />
            </Form.Item>
            <Form.Item
              wrapperCol={{ span: 24 }}>
              <Button
                loading={loading}
                type="primary"
                htmlType="submit"
                className="login-form-button"
                style={{ width: '100%' }}
              >
                登&nbsp;录
              </Button>
            </Form.Item>
          </Form>
        </div>
      </div>
    )
  }
}
